package ua.pp.parkee.t2;

import java.nio.BufferOverflowException;
import java.nio.BufferUnderflowException;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by parkee on 05.06.14.
 */
public class CircularBuffer<E> {

    private E[] buffer;
    private Integer start;
    private Integer end;
    private Integer size;

    private final Lock lock = new ReentrantLock();
    private final Condition isFull = lock.newCondition();
    private final Condition isEmpty = lock.newCondition();

    public CircularBuffer(Integer n) {
        buffer = (E[]) new Object[n];
        start = 0;
        end = 0;
        size = 0;
    }



    public void add(E e) {
        lock.lock();
        try {

            while (isFull()) {
                try {
                    isEmpty.await();
                } catch (InterruptedException ex) {
                    //Ignore
                }
            }

            if(!size.equals(buffer.length)) {
                buffer[end++] = e;
                end %= buffer.length;
                size++;
            } else {
                throw new BufferOverflowException();
            }
            isFull.signal();
        } finally {
            lock.unlock();
        }

    }

    public E get() {

        lock.lock();
        E e;

        try {

            while (isEmpty()) {
                try {
                    isFull.await();
                } catch (InterruptedException ex) {
                    //Ignore
                }
            }

            if (!size.equals(0)) {
                e = buffer[start++];
                start %= buffer.length;
                size--;
            } else {
                throw new BufferUnderflowException();
            }
            isEmpty.signal();
        } finally {
            lock.unlock();
        }

        return e;
    }

    public Boolean isEmpty() {
        return size.equals(0);
    }

    public Boolean isFull() {
        return size.equals(buffer.length);
    }
}
